package util;


import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author: wenjingyuan
 * @Date: 2023/03/18/20:17
 * @Description:工具类
 */
public class DBUtils {
    private static volatile MysqlDataSource mysqlDataSource;
    //private static  volatile Connection connection;
    private static MysqlDataSource getMysqlDataSource(){

        //双重锁的校验
        if(mysqlDataSource==null){
            synchronized (DBUtils.class){
                if(mysqlDataSource==null){
                    mysqlDataSource=new MysqlDataSource();
                    mysqlDataSource.setURL("jdbc:mysql://localhost:3306/myblog2023?characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8");
                    mysqlDataSource.setUser("root");
                    mysqlDataSource.setPassword("12345678");
                }
            }
        }
        return mysqlDataSource;
    }
    /**
     * 两种模式单例模式connection+多例模式connection(当前我们实现的是多例模式)
     *yewuliangxiao yongdanli
     * yewuliangda yongduoli
     */
    public static Connection getConnection() throws SQLException {
        Connection connection= (Connection) getMysqlDataSource().getConnection();
        return connection;
    }
    //关闭资源的方法
    public static void close(ResultSet resultSet, PreparedStatement statement,Connection connection) throws SQLException {
        if(resultSet!=null)resultSet.close();
        if(statement!=null)statement.close();
        if(connection!=null)connection.close();
    }
}
